package com.ztomorrow.ying_cun_plus.utils;

import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import static com.ztomorrow.ying_cun_plus.constant.front.CacheConstant.REDIS_VERIFY_CODE;
import static com.ztomorrow.ying_cun_plus.constant.front.CacheConstant.REDIS_VERIFY_CODE_TTL;

@Component
@RequiredArgsConstructor
public class RedisVerifyCode {

    private  final StringRedisTemplate stringRedisTemplate;

    /**
     * 获取验证码以及图片，并将验证码放入redis
     * @param id 当前会话唯一ID
     * @return 验证码图片
     */
    public String generateVerifyCode(String id) throws IOException {
        String code = ImgVerifyCodeUtils.generateVerifyCode(4);
        stringRedisTemplate.opsForValue().set(REDIS_VERIFY_CODE + id, code,
                REDIS_VERIFY_CODE_TTL, TimeUnit.MINUTES);
        return ImgVerifyCodeUtils.getVerifyCodeImage(code);
    }

    /**
     * 检查验证码的正确性
     * @param id 当前会话唯一ID
     * @param code 验证码
     */
    public boolean checkVerifyCode(String id, String code){
        return Objects.equals(
                stringRedisTemplate.opsForValue().get(REDIS_VERIFY_CODE + id)
                , code);
    }

    /**
     * 验证结束后，主动删除缓存
     * @param id 当前会话唯一ID
     */
    public void delVerifyCode(String id){
        stringRedisTemplate.delete(REDIS_VERIFY_CODE + id);
    }
}
